package org.tang.springcloudvv.gateway.service;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p><em>Created on 2022/4/8 7:01 下午</em></p>
 *
 * @author fuzhongtang
 * @since 1.0.1
 */
@Service
public class DiscoveryClientService {

    @Autowired
    private DiscoveryClient discoveryClient;
    protected Logger logger = LoggerFactory.getLogger(getClass());


    public List<Object> getServerList() {
        List<Object> listAll = new ArrayList<Object>();
        List<String> list = discoveryClient.getServices();
        listAll.add(list);//显示所有serviceId
        for (String serviceId:list) {
            List<ServiceInstance> listService = discoveryClient.getInstances(serviceId);
            listAll.addAll(listService);
        }

        String discoveryClientInfo = "discoveryClient=" + discoveryClient.getClass().getName();
        listAll.add(discoveryClientInfo);
        Object json = JSONObject.toJSON(listAll);
        logger.info(json.toString());
        return listAll;
    }
}
